﻿// 添加beforesetvalue,afterclearValue事件
Ext.override(Ext.form.ComboBox, {
	clearValue: function () {
		if (this.hiddenField) {
			this.hiddenField.value = '';
		}
		this.setRawValue('');
		this.lastSelectionText = '';
		this.applyEmptyText();
		this.value = '';
		this.fireEvent('afterclearValue'); // caoyang添加事件 主要用途:清空combobox显示框数据后,在方法中对依赖combobox已选择数据的显示元素进行处理
	},
	setValue: function (v) {
		var text = v;
		if (this.valueField) {
			var r = this.findRecord(this.valueField, v);
			if (r) {
				this.fireEvent('beforesetvalue', r); // zhangxian添加事件
				text = r.data[this.displayField];
			} else if (Ext.isDefined(this.valueNotFoundText)) {
				text = this.valueNotFoundText;
			}
		}
		this.lastSelectionText = text;
		//alert('Hiddenfield [' + this.hiddenField.value + '] new value is :' + v);
		//if (this.hiddenField && this.hiddenField.value == '') {
		if (this.hiddenField) {
			this.hiddenField.value = v;
		}
		Ext.form.ComboBox.superclass.setValue.call(this, text);
		this.value = v;
		return this;
	},
	// private
	initComponent: function () {
		Ext.form.ComboBox.superclass.initComponent.call(this);
		this.addEvents('beforesetvalue', 'afterclearValue',
		/**
		* @event expand Fires when the dropdown list is
		*        expanded
		* @param {Ext.form.ComboBox}
		*            combo This combo box
		*/
						'expand',
		/**
		* @event collapse Fires when the dropdown list is
		*        collapsed
		* @param {Ext.form.ComboBox}
		*            combo This combo box
		*/
						'collapse',
		/**
		* @event beforeselect Fires before a list item is
		*        selected. Return false to cancel the
		*        selection.
		* @param {Ext.form.ComboBox}
		*            combo This combo box
		* @param {Ext.data.Record}
		*            record The data record returned from the
		*            underlying store
		* @param {Number}
		*            index The index of the selected item in
		*            the dropdown list
		*/
						'beforeselect',
		/**
		* @event select Fires when a list item is selected
		* @param {Ext.form.ComboBox}
		*            combo This combo box
		* @param {Ext.data.Record}
		*            record The data record returned from the
		*            underlying store
		* @param {Number}
		*            index The index of the selected item in
		*            the dropdown list
		*/
						'select',
		/**
		* @event beforequery Fires before all queries are
		*        processed. Return false to cancel the query or
		*        set the queryEvent's cancel property to true.
		* @param {Object}
		*            queryEvent An object that has these
		*            properties:
		*            <ul>
		*            <li><code>combo</code> :
		*            Ext.form.ComboBox <div
		*            class="sub-desc">This combo box</div></li>
		*            <li><code>query</code> : String <div
		*            class="sub-desc">The query</div></li>
		*            <li><code>forceAll</code> : Boolean
		*            <div class="sub-desc">True to force "all"
		*            query</div></li>
		*            <li><code>cancel</code> : Boolean <div
		*            class="sub-desc">Set to true to cancel the
		*            query</div></li>
		*            </ul>
		*/
						'beforequery');
		if (this.transform) {
			var s = Ext.getDom(this.transform);
			if (!this.hiddenName) {
				this.hiddenName = s.name;
			}
			if (!this.store) {
				this.mode = 'local';
				var d = [], opts = s.options;
				for (var i = 0, len = opts.length; i < len; i++) {
					var o = opts[i], value = (o.hasAttribute ? o
									.hasAttribute('value') : o
									.getAttributeNode('value').specified)
									? o.value
									: o.text;
					if (o.selected && Ext.isEmpty(this.value, true)) {
						this.value = value;
					}
					d.push([value, o.text]);
				}
				this.store = new Ext.data.ArrayStore({
					'id': 0,
					fields: ['value', 'text'],
					data: d,
					autoDestroy: true
				});
				this.valueField = 'value';
				this.displayField = 'text';
			}
			s.name = Ext.id(); // wipe out the name in case somewhere
			// else they have a reference
			if (!this.lazyRender) {
				this.target = true;
				this.el = Ext.DomHelper.insertBefore(s, this.autoCreate
										|| this.defaultAutoCreate);
				this.render(this.el.parentNode, s);
				Ext.removeNode(s); // remove it
			} else {
				Ext.removeNode(s); // remove it
			}
		}
		// auto-configure store from local array data
		else if (this.store) {
			this.store = Ext.StoreMgr.lookup(this.store);
			if (this.store.autoCreated) {
				this.displayField = this.valueField = 'field1';
				if (!this.store.expandData) {
					this.displayField = 'field2';
				}
				this.mode = 'local';
			}
		}

		this.selectedIndex = -1;
		if (this.mode == 'local') {
			if (!Ext.isDefined(this.initialConfig.queryDelay)) {
				this.queryDelay = 10;
			}
			if (!Ext.isDefined(this.initialConfig.minChars)) {
				this.minChars = 0;
			}
		}
	}

});

Ext.override(Ext.form.CheckboxGroup, {
	setValueForItem: function (val) {
		val = String(val).split(',');
		this.items.each(function (item) {
			item.setValue(false);   //初始化，現將所有的checkbox設為未選定。
		});
		//this.items.each()<====>this.eachItem();

		this.items.each(function (item) {
			if (val.indexOf(item.inputValue) > -1) {   //從數據庫中提取數據，與頁面上checkbox的inputValue對比來判斷是否選中。
				item.setValue(true);    //可理解為以下：
			}
			/*
			等價于：
			for(var i=0;i<val.length;i++){
			if(var[i]==item.inputValue){
			item.setValue(true);
			}
			}    
			*/
		});
	}
});

//此部份是爲了讓BasicForm能夠找到不只是FormField，讓他能夠試用于radiogroup、checkboxgroup的情況.
Ext.override(Ext.form.BasicForm, {
	findField: function (id) {
		var field = this.items.get(id);
		if (!field) {
			// --------- It was: ---------
			// //Iterate through children on first level
			// this.items.each(function(f){
			//     if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){
			//         field = f;
			//         return false;
			//     }
			// });

			// --------- It is now: ---------
			// Iterate through children on all levels
			var fn = function (f) {
				if (field)
					return false;   //stop iteration, if field was found already

				if (f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)) {
					field = f;    // field was found
					return false;
				}
				else if (f.items) {
					f.items.each(fn);   // iterate through child items
				}
			}
			this.items.each(fn);
			// --------- End of my changes ---------
		}
		return field || null;
	},

	updateRecord: function (record) {
		//既然已經能夠試用于radiogroup、checkboxgroup了！那麼在Form中當然就要對其設置獲取的值啦！
		record.beginEdit();
		var fs = record.fields;
		fs.each(function (f) {
			var field = this.findField(f.name);
			if (field) {
				var value = field.getValue();

				if (value.getGroupValue) {
					value = value.getGroupValue();

				} else if (field.eachItem) {
					var re = "";
					field.eachItem(function (item) {
						if (item.getValue() == true) {
							re += item.inputValue + ",";
						}
					});
					if (re.length > 0) {
						value = re.substr(0, re.length - 1);
					} else {
						value = re
					}
				}
				record.set(f.name, value);
			}
		}, this);
		record.endEdit();
		return this;
	}
});
